package com.le.tester.sevice.impl;

import com.le.tester.common.ServerResponse;
import com.le.tester.common.enums.RedisKey;
import com.le.tester.common.enums.ResponseCode;
import com.le.tester.dao.ProductMapper;
import com.le.tester.entity.Product;
import com.le.tester.sevice.ProductService;
import com.le.tester.utils.RedisUtil;
import com.le.tester.utils.auth.RequestLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：产品的实现逻辑层
 */
@Service
public class ProductServiceImpl implements ProductService {


    @Resource
    private ProductMapper productMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取所有的产品信息
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, List<Product>> getProductInfo() {

        Object productInfo = redisUtil.get(RedisKey.PRODUCT_ALL.getCode());
        Map<String, List<Product>> resultMap = new HashMap<>();
        List<Product> products;
        if (null == productInfo) {
            products = productMapper.selectProductInfo();
            redisUtil.set(RedisKey.PRODUCT_ALL.getCode(), products, 30 * 60);
            //startTime = System.currentTimeMillis();
        } else {
            products = (List<Product>) redisUtil.get(RedisKey.PRODUCT_ALL.getCode());
            //startTime = System.currentTimeMillis();
        }
        resultMap.put("productInfo", products);
        //System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
        return resultMap;
    }

    //根据主键获取产品信息
    @Override
    public ServerResponse<Product> getProductInfoById(Long productId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(), product);
    }

    //保存产品信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse<Long> saveProduct(Product product) {
        long result;
        if (Objects.isNull(product.getId())) {
            //新增
            result = productMapper.insert(product);
        } else {
            //更新
            result = productMapper.updateByPrimaryKey(product);
        }
        return ServerResponse.createBySuccess(result);
    }
}
